package com.fick.struts.action;

/**
 * 角色权限管理
 * add by 王浩强
 */
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Query;
import org.hibernate.Session;

import com.fick.hibernate.dao.RoleDAO;
import com.fick.hibernate.dao.RoleMenuDAO;
import com.fick.hibernate.dao.SysMenuDAO;
import com.fick.hibernate.model.Role;
import com.fick.hibernate.model.RoleMenu;
import com.fick.hibernate.model.SysMenu;

public class RoleMenuAction extends DispatchAction {

	private static final Log log = LogFactory.getLog(RoleMenuAction.class);

	private RoleMenuDAO dao = new RoleMenuDAO();

	public ActionForward rm(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String roleId = request.getParameter("roleId");
		String menus[] = request.getParameterValues("menus");
		if (roleId != null && roleId.length() > 0 && menus != null) {
			// 先删除原有权限
			Session session = dao.getSession();
			session.beginTransaction();
			Query query = session.createQuery("delete from RoleMenu where roleId.id=" + roleId);
			query.executeUpdate();
			session.getTransaction().commit();
			// 添加新权限
			if (menus.length > 0) {
				Role role = new RoleDAO().findById(Integer.parseInt(roleId));
				if (role != null) {
					SysMenu menu;
					SysMenuDAO menuDAO = new SysMenuDAO();
					for (int i = 0; i < menus.length; i++) {
						RoleMenu roleMenu = new RoleMenu();
						menu = menuDAO.findById(Integer.parseInt(menus[i]));
						if (menu != null) {
							roleMenu.setMenuId(menu);
						}
						roleMenu.setRoleId(role);
						dao.save(roleMenu);
					}
				}
			}
		}
		request.getSession().setAttribute("message", "修改成功!");
		response.sendRedirect("role_menu.jsp?roleid=" + roleId);
		return null;
	}
}
